/**
 * DeadLock
 *
 * @author Darksiderl
 * @date 2018/2/26
 *
 * 死锁
 *
 * 死锁的条件
 * 1.互斥使用 Work1锁住objA的时候，Work2不能使用
 * 2.不可抢占 Work2不能抢占Work1的objA资源，只能等待Work1主动释放objA
 * 3.请求和保持 线程在请求其他资源的同时还占有着原来的资源Work1在请求objB的时候还占有着objA
 * 4.循环等待 Work1锁住了objA等待Work2释放objB,Work2锁住了objB等待Work1释放objA
 */
public class DeadLock {

    public static String objA = "objA";
    public static String objB = "objB";

    public static void main(String[] args) {

        Work1 work1 = new Work1();
        Work2 work2 = new Work2();

        new Thread(work1).start();
        new Thread(work2).start();

    }

    static class Work1 implements Runnable {

        @Override
        public void run() {
            System.out.println("Work1开始运行");
            try {
                while (true) {
                    synchronized (objA) {
                        System.out.println("Work1 锁住了 objA");

                        Thread.sleep(3000);
                        synchronized (objB) {
                            System.out.println("Work1 锁住了 objB");
                        }

                    }

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }


    static class Work2 implements Runnable {

        @Override
        public void run() {
            System.out.println("Work2开始运行");
            try {
                while (true) {
                    synchronized (objB) {
                        System.out.println("Work2 锁住了 objB");

                        Thread.sleep(3000);
                        synchronized (objA) {
                            System.out.println("Work2 锁住了 objA");
                        }

                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
